import { setStorage, getStorage } from '@lib/util'
import { _getMenus } from '_api'

export default {
  state: {
    token: getStorage('token') ? getStorage('token') : '',
    userInfo: getStorage('userInfo') ? getStorage('userInfo') : {},
    menuList: getStorage('menuList') ? getStorage('menuList') : []
  },
  mutations: {
    //存储路由
    setMenuList (state, list)  {
      let arr = [
        {
          menuName:'首页',
          menuUrl:'/home',
          name:'home',
          icon:'el-icon-s-home',
          meta:{
            title:'首页 | 规范平台操作管理系统',
          }
        }
      ]
      setStorage('menuList', arr.concat(list))
      state.menuList = arr.concat(list)
    },
    setToken (state, token) {
      setStorage('token', token)
      state.token = token
    },
    setUserInfo (state, userInfo) {
      setStorage('userInfo', userInfo)
      state.userInfo = userInfo
    },
    clearStorage (state) {
      localStorage.removeItem('userInfo')
      localStorage.removeItem('menuList')
      localStorage.removeItem('token')
      state.token = ''
      state.userInfo = {}
      state.menuList = []
    }
  },
  actions: {
    updateMenuList ({ state, commit }) {
      return new Promise((resolve, reject) => {
        _getMenus(state.userInfo.userId).then(res => {
          commit('setMenuList', res.data)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}
